﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Sinacor.Infra.Tools.ServiceRegistration.Business
{
    public class Module
    {
        #region Attributes

        private Data.Module _resourceAccess;
        private object locker = new object();

        #endregion

        #region Constructor

        public Module()
        {
            this._resourceAccess = new Data.Module();
        }

        #endregion

        #region Methods

        public DataSet SelectAll()
        {
            return _resourceAccess.SelectAll();
        }

        public List<Entity.Module> SelectAll(Entity.Module entity)
        {
            return _resourceAccess.SelectAll(entity);
        }
                
        public List<Entity.Module> SelectModule(Entity.Module entity)
        {
            return _resourceAccess.SelectModule(entity);
        }

        public Entity.Module PersistModule(Entity.Module entity)
        {
            Entity.Module module = new Entity.Module() { ModuleName = entity.ModuleName };
            List<Entity.Module> modules = null;

            modules = _resourceAccess.SelectModule(module);

            if (modules.Count == 0)
            {
                module = InsertModule(entity);
            }
            else
            {
                module = modules[0];

                module.DateChange = entity.DateChange;
                module.DataOrigin = entity.DataOrigin;
                UpdateModule(module);
            }

            return module;
        }

        public Entity.Module InsertModule(Entity.Module entity)
        {
            entity.ModuleId = this.GetNextModuleId();
            return _resourceAccess.InsertModule(entity);
        }

        public void UpdateModule(Entity.Module entity)
        {
            _resourceAccess.UpdateModule(entity);
        }

        public void DeleteModule(Entity.Module entity)
        {
            _resourceAccess.DeleteModule(entity);
        }

        public int GetNextModuleId()
        {
            int nextId = 0;

            lock (locker)
            {
                nextId = _resourceAccess.GetNextModuleId();
            }

            return nextId;
        }

        #endregion
    }
}
